#pragma once

//对信号量相关接口的封装
#include <iostream>
#include <semaphore.h>

namespace SemModule
{
    int default_sem_value = 1;

    class Sem
    {
    public:
        Sem(int value = default_sem_value):_init_value(value)
        {
            int n = ::sem_init(&_sem, 0, _init_value);
            if(n != 0)
            {
                std::cout << "sem init error" << std::endl;
            }
        }
        //P操作就是申请相应的资源，即等待条件的满足，相应资源数--
        void P()
        {
            int n = ::sem_wait(&_sem);
            if(n != 0)
            {
                std::cout << "sem wait error" << std::endl;
            }
        }
        //V操作就是释放相应的资源，相应资源数++
        void V()
        {
            int n = ::sem_post(&_sem);
            if(n != 0)
            {
                std::cout << "sem post error" << std::endl;
            }
        }
        ~Sem()
        {
            int n = ::sem_destroy(&_sem);
            if(n != 0)
            {
                std::cout << "sem destroy error" << std::endl;
            }
        }
    private:
        sem_t _sem;
        int _init_value;
    };
}